package com.whmskj.xjlhsc.gongweiji.maintenancedynamics.service.imp;

import com.whmskj.xjlhsc.gongweiji.maintenancedynamics.mapper.GwjMaintenanceDynamicsMapper;
import com.whmskj.xjlhsc.gongweiji.maintenancedynamics.pojo.*;
import com.whmskj.xjlhsc.gongweiji.maintenancedynamics.service.IGwjMaintenanceDynamicsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author jiaruchun
 * @date 2025-10-09 15:40
 */
@Slf4j
@Service
public class GwjMaintenanceDynamicsServiceImpl implements IGwjMaintenanceDynamicsService {

    @Autowired
    private GwjMaintenanceDynamicsMapper gwjMaintenanceDynamicsMapper;

    /**
     * @param gwjMaintenanceDynamicsDTO
     * @return
     */
    @Override
    public GwjMaintenanceDynamicsVO getMaintenance(GwjMaintenanceDynamicsDTO gwjMaintenanceDynamicsDTO) {
        String month = gwjMaintenanceDynamicsDTO.getMonth(); // yyyy-MM
        String start;
        String end;

        LocalDateTime now = LocalDateTime.now();
        YearMonth yearMonth;
        if (month == null || month.isEmpty()) {
            yearMonth = YearMonth.from(now);
        } else {
            yearMonth = YearMonth.parse(month); // 解析 yyyy-MM
        }

// 当前月的20号 21:30
        LocalDateTime curMonth20_2130 = yearMonth.atDay(20).atTime(21, 30);

// 上个月的20号
        LocalDate prevMonth20 = yearMonth.minusMonths(1).atDay(20);

        if (yearMonth.equals(YearMonth.from(now))) {
            // 如果传入的month是当前月
            if (now.isAfter(curMonth20_2130)) {
                // 已经过了本月20号21:30
                end = now.toLocalDate().toString();
                start = yearMonth.atDay(20).toString();
            } else {
                // 还没到本月20号21:30
                end = yearMonth.atDay(20).toString();
                start = prevMonth20.toString();
            }
        } else {
            // 非当前月
            start = prevMonth20.toString();
            end = yearMonth.atDay(20).toString();
        }
        List<GwjMaintenanceDynamicsDeVO> gwjMaintenanceDynamicsDeVOList = gwjMaintenanceDynamicsMapper.getByName(start,end,gwjMaintenanceDynamicsDTO.getProcess());
        log.info("gwjMaintenanceDynamicsDeVOList:{}",gwjMaintenanceDynamicsDeVOList);
        //组装VO
        GwjMaintenanceDynamicsVO vo = new GwjMaintenanceDynamicsVO();
        if (gwjMaintenanceDynamicsDeVOList != null && !gwjMaintenanceDynamicsDeVOList.isEmpty()) {
            // 按项目名称分组
            Map<String, List<GwjMaintenanceDynamicsDeVO>> groupedByProject = gwjMaintenanceDynamicsDeVOList.stream()
                    .collect(Collectors.groupingBy(GwjMaintenanceDynamicsDeVO::getProjectName));

            // 转换为List<ByProjectName>
            List<ByProjectName> byProjectNameList = new ArrayList<>();
            for (Map.Entry<String, List<GwjMaintenanceDynamicsDeVO>> entry : groupedByProject.entrySet()) {
                ByProjectName byProjectName = new ByProjectName();
                byProjectName.setProjectName(entry.getKey());

                // 按日期分组，然后转换为List<DailySchedule>
                Map<String, List<GwjMaintenanceDynamicsDeVO>> groupedByDate = entry.getValue().stream()
                        .collect(Collectors.groupingBy(GwjMaintenanceDynamicsDeVO::getDateAndWeekday));

                List<DailySchedule> dailySchedules = new ArrayList<>();
                for (Map.Entry<String, List<GwjMaintenanceDynamicsDeVO>> dateEntry : groupedByDate.entrySet()) {
                    DailySchedule dailySchedule = new DailySchedule();
                    dailySchedule.setDateAndWeekday(dateEntry.getKey());

                    // 将同一天的数据转换为ScheduleVOS列表
                    List<ScheduleVOS> scheduleList = dateEntry.getValue().stream()
                            .map(devo -> {
                                ScheduleVOS scheduleVO = new ScheduleVOS();
                                scheduleVO.setMachineNo(devo.getDeviceMachineNumber());
                                scheduleVO.setCompleteStatus(devo.getCompletionStatus());
                                return scheduleVO;
                            })
                            .collect(Collectors.toList());

                    dailySchedule.setScheduleList(scheduleList);
                    dailySchedules.add(dailySchedule);
                }
                //dailySchedules按dateAndWeekday的日期部分MM-dd排序
                dailySchedules.sort((d1, d2) -> {
                    String date1Str = d1.getDateAndWeekday().substring(0, 5);
                    String date2Str = d2.getDateAndWeekday().substring(0, 5);
                    return date1Str.compareTo(date2Str);
                });
                byProjectName.setDailySchedules(dailySchedules);
                byProjectNameList.add(byProjectName);
            }
            vo.setByProjectNameList(byProjectNameList);
            //按机台汇总---------------------------------------------
            Map<String, List<GwjMaintenanceDynamicsDeVO>> groupedByMachine = gwjMaintenanceDynamicsDeVOList.stream()
                    .collect(Collectors.groupingBy(GwjMaintenanceDynamicsDeVO::getDeviceMachineNumber));
            // 转换为List<ByMachine>
            List<ByMachine> byMachineList = new ArrayList<>();
            for (Map.Entry<String, List<GwjMaintenanceDynamicsDeVO>> entry : groupedByMachine.entrySet()) {
                ByMachine byMachine = new ByMachine();
                byMachine.setMachineNo(entry.getKey());

                // 按日期分组，然后转换为List<DailySchedule>
                Map<String, List<GwjMaintenanceDynamicsDeVO>> groupedByDate = entry.getValue().stream()
                        .collect(Collectors.groupingBy(GwjMaintenanceDynamicsDeVO::getDateAndWeekday));

                List<DailySchedule2> dailySchedules = new ArrayList<>();
                for (Map.Entry<String, List<GwjMaintenanceDynamicsDeVO>> dateEntry : groupedByDate.entrySet()) {
                    DailySchedule2 dailySchedule = new DailySchedule2();
                    dailySchedule.setDateAndWeekday(dateEntry.getKey());

                    // 将同一天的数据转换为ScheduleVOS列表
                    List<ScheduleVOS2> scheduleList = dateEntry.getValue().stream()
                            .map(devo -> {
                                ScheduleVOS2 scheduleVO = new ScheduleVOS2();
                                scheduleVO.setProjectName(devo.getProjectName());
                                scheduleVO.setCompleteStatus(devo.getCompletionStatus());
                                return scheduleVO;
                            })
                            .collect(Collectors.toList());

                    dailySchedule.setScheduleList(scheduleList);
                    dailySchedules.add(dailySchedule);
                }
                //dailySchedules按dateAndWeekday的日期部分MM-dd排序
                dailySchedules.sort((d1, d2) -> {
                    String date1Str = d1.getDateAndWeekday().substring(0, 5);
                    String date2Str = d2.getDateAndWeekday().substring(0, 5);
                    return date1Str.compareTo(date2Str);
                });
                byMachine.setDailyScheduleList(dailySchedules);
                byMachineList.add(byMachine);
            }
            vo.setByMachineList(byMachineList);
        }else {
            vo.setByProjectNameList(Collections.EMPTY_LIST);
                vo.setByMachineList(Collections.EMPTY_LIST);
        }
        return vo;
    }
}
